package pb

import (
	"strings"

	"github.com/xuender/oils/base"
	"github.com/xuender/oils/ios"
)

func NewInterrupts() ([]*Interrupts, error) {
	ints := []*Interrupts{}
	cpus := 0

	return ints, ios.ReadLine("/proc/interrupts", func(line string) error {
		if cpus == 0 {
			cpus = len(strings.Fields(line))

			return nil
		}

		fields := strings.Fields(line)
		description := ""
		var counts uint64

		for i := 1; i <= cpus; i++ {
			if len(fields) <= i {
				continue
			}

			count, err := base.ParseInteger[uint64](fields[i])
			if err != nil {
				return err
			}

			counts += count
		}

		if len(fields) > cpus {
			description = strings.Join(fields[cpus+1:], " ")
		}

		ints = append(ints, &Interrupts{
			Name:        fields[0][:len(fields[0])-1],
			Counts:      counts,
			Description: description,
		})

		return nil
	})
}
